import axios, { Method, AxiosResponse, AxiosRequestConfig } from "axios";

type ApiResponse<T = any> =
  | { success: true; data: T; status: number }
  | { success: false; error: ApiError };

type ApiError = {
  message: string;
  status: number;
  code?: string;
};

// 创建axios实例
const apiClient = axios.create({
  baseURL: "http://localhost:8000",
  timeout: 30000, // 文件上传需要更长时间
});

// 智能内容类型推断
function detectContentType(data: unknown): string {
  if (data instanceof FormData) {
    return "multipart/form-data";
  }
  if (typeof data === "object" && data !== null) {
    return "application/json";
  }
  return "text/plain";
}

// 增强版请求函数
export async function callApi<T = any>(
  path: string,
  method: Method = "GET",
  data?: unknown,
  customConfig: AxiosRequestConfig = {}
): Promise<ApiResponse<T>> {
  try {
    // 自动设置Content-Type
    const headers = {
      ...customConfig.headers,
      "Content-Type": customConfig.headers?.["Content-Type"] || detectContentType(data),
    };

    const config: AxiosRequestConfig = {
      url: path,
      method,
      headers,
      ...customConfig,
      withCredentials:true,
      ...(method.toLowerCase() === "get" ? { params: data } : { data }),
    };

    const response: AxiosResponse<T> = await apiClient.request(config);

    return {
      success: true,
      data: response.data,
      status: response.status,
    };
  } catch (error) {
    return handleApiError(error);
  }
}

// 错误处理函数
function handleApiError(error: unknown): ApiResponse {
  if (axios.isAxiosError(error)) {
    const status = error.response?.status || 0;
    return {
      success: false,
      error: {
        message: getErrorMessage(status),
        status,
        code: error.code || String(status),
      },
    };
  }

  return {
    success: false,
    error: {
      message: "未知错误",
      status: 0,
      code: "UNKNOWN_ERROR",
    },
  };
}

// 错误信息映射
function getErrorMessage(status: number): string {
  const messages: Record<number, string> = {
    400: "请求参数错误",
    401: "身份验证失败",
    403: "拒绝访问",
    404: "资源未找到",
    413: "文件体积过大",
    415: "不支持的媒体类型",
    500: "服务器内部错误",
    502: "网关错误",
    503: "服务不可用",
    504: "网关超时",
  };
  return messages[status] || `请求失败 (状态码: ${status})`;
}

axios.interceptors.request.use(config => {
  const token = localStorage.getItem('access_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

axios.interceptors.response.use(response => response, async error => {
  const originalRequest = error.config;

  if (error.response?.status === 401 && !originalRequest._retry) {
    originalRequest._retry = true;

    // 调用刷新令牌接口
    const newToken = await refreshAccessToken();
    localStorage.setItem('access_token', newToken);

    // 重试原始请求
    originalRequest.headers.Authorization = `Bearer ${newToken}`;
    return axios(originalRequest);
  }

  return Promise.reject(error);
});

const refreshAccessToken = async () => {
  const refresh_token = localStorage.getItem('access_token');
  const response:any = await callApi('/refresh/','POST',{refresh_token:refresh_token});
  return response.data.access_token;
};